//
//  MOCaiPuViewController.m
//  MobileOffice
//
//  Created by 冰冰 on 2019/10/22.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOCaiPuViewController.h"
#import "MOCaiPuViewCell.h"

@interface MOCaiPuViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,strong)NSArray *canTingArray;

@property(nonatomic,strong)UIButton *canTingButton;

@property(nonatomic,strong)NSString *restaurantId;


@end

@implementation MOCaiPuViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatNav];
    
    [self creatView];
    
    [self initData];
}

-(void)creatNav
{
    self.canTingButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 91, 30)];
    self.canTingButton.titleLabel.font = FONT_SIZE(13);
    [self.canTingButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentRight)];
    [self.canTingButton setTitleColor:KBlackColor_2A2A2A forState:UIControlStateNormal];
    [self.canTingButton addTarget:self action:@selector(clickCanTingButton) forControlEvents:UIControlEventTouchUpInside];
    [self.canTingButton setImage:IMAGE(@"can_down") forState:UIControlStateNormal];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.canTingButton];
}

-(void)creatView
{
    self.title = @"菜谱";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    view.backgroundColor = KGrayColor_f8f8f8;
    self.tableView.tableHeaderView = view;
}

-(void)initData
{
    //餐厅
    NSString *postUrl1 = [NSString stringWithFormat:@"%@?&authorization=%@&userId=%@",GETRESTAURANTLIST,[NSString URLEncodedString:[MOUser sharedMOUser].token],[MOUser sharedMOUser].userName];
    [PPNetworkHelper POST:postUrl1 parameters:nil success:^(id responseObject) {
        NSLog(@"餐厅：%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSArray class]]) {
            self.canTingArray = responseObject;
            if (self.canTingArray.count>0) {
                [self.canTingButton setTitle:self.canTingArray[0][@"restaurantName"] forState:UIControlStateNormal];
                [self.canTingButton SG_imagePositionStyle:(SGImagePositionStyleRight) spacing:10];
                self.restaurantId = self.canTingArray[0][@"restaurantId"];
                
                [self getCaiPuData];
            }
        }
        
    } failure:^(NSError *error) {
        NSLog(@"餐厅：%@",[error localizedDescription]);
    }];
    
}

-(void)getCaiPuData
{
    //菜谱
    NSString *postUrl = [NSString stringWithFormat:@"%@?&authorization=%@&userId=%@",GETECIPEBYRESAURANID,[NSString URLEncodedString:[MOUser sharedMOUser].token],[MOUser sharedMOUser].userName];
    [PPNetworkHelper POST:postUrl parameters:@{@"restaurantId":self.restaurantId} success:^(id responseObject) {
        NSLog(@"菜谱：%@",responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            
            NSArray *dateArray = responseObject[@"result"];
            self.dataArray = [NSMutableArray array];
            for (int i = 0; i<dateArray.count; i++) {
                NSDictionary *dateDic = dateArray[i];
                NSMutableDictionary *muDic1 = [NSMutableDictionary dictionary];
                [muDic1 setObject:@"0" forKey:@"isOpen"];
                [muDic1 setObject:dateDic.allKeys[0] forKey:@"name"];
                
                NSArray *typeArray = dateDic[dateDic.allKeys[0]];
                NSMutableArray *typeMuArray = [NSMutableArray array];
                for (int j = 0; j<typeArray.count; j++) {
                    NSDictionary *typeDic = typeArray[j];
                    MOCaiPuModel *model = [[MOCaiPuModel alloc]init];
                    model.open = @"0";
                    model.typeStr = typeDic.allKeys[0];
                    
                    NSArray *foodArray = typeDic[typeDic.allKeys[0]];
                    NSMutableArray *foodMuArray = [NSMutableArray array];
                    for (int k = 0; k<foodArray.count; k++) {
                        [foodMuArray addObject:foodArray[k][@"dishName"]];
                    }
                    model.arr = foodMuArray;
                    
                    [typeMuArray addObject:model];
                }
                
                [muDic1 setObject:typeMuArray forKey:@"arr"];
                
                [self.dataArray addObject:muDic1];
            }
            [self.tableView reloadData];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"菜谱：%@",[error localizedDescription]);
    }];
    
//    NSArray *dateArray = @[@"2019-20-23",@"2019-20-21",@"2019-20-20"];
//    self.dataArray = [NSMutableArray array];
//    for (int i = 0; i<dateArray.count; i++) {
//        NSMutableDictionary *muDic1 = [NSMutableDictionary dictionary];
//        [muDic1 setObject:@"0" forKey:@"isOpen"];
//        [muDic1 setObject:dateArray[i] forKey:@"name"];
//
//        NSArray *typeArray = @[@"1",@"2",@"3",@"4"];
//        NSMutableArray *typeMuArray = [NSMutableArray array];
//        for (int j = 0; j<typeArray.count; j++) {
//            MOCaiPuModel *model = [[MOCaiPuModel alloc]init];
//            model.open = @"0";
//            model.typeStr = typeArray[j];
//
//            NSArray *foodArray = @[@"红烧肉",@"红烧排骨",@"炝炒白菜"];
//            NSMutableArray *foodMuArray = [NSMutableArray array];
//            for (int k = 0; k<foodArray.count; k++) {
//                [foodMuArray addObject:foodArray[k]];
//            }
//            model.arr = foodMuArray;
//
//            [typeMuArray addObject:model];
//        }
//
//        [muDic1 setObject:typeMuArray forKey:@"arr"];
//
//        [self.dataArray addObject:muDic1];
//    }
//    [self.tableView reloadData];
}


-(void)clickSectionOpenButton:(UIButton *)sender
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataArray[sender.tag]];
    if ([dic[@"isOpen"] integerValue]==1) {
        [dic setObject:@"0" forKey:@"isOpen"];
    }else{
        [dic setObject:@"1" forKey:@"isOpen"];
    }
    [self.dataArray replaceObjectAtIndex:sender.tag withObject:dic];
    [self.tableView reloadData];
}

-(void)clickCanTingButton
{
    SNXYSelectedNumberView *pickview = [[SNXYSelectedNumberView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    NSMutableArray *muArr = [NSMutableArray array];
    for (int i = 0; i<self.canTingArray.count; i++) {
        [muArr addObject:self.canTingArray[i][@"restaurantName"]];
    }
    pickview.numberArray = [NSArray arrayWithArray:muArr];
    __weak typeof (self)weakSelf = self;
    pickview.clickIndexBlock = ^(NSInteger index) {
        [weakSelf.canTingButton setTitle:weakSelf.canTingArray[0][@"restaurantName"] forState:UIControlStateNormal];
        [weakSelf.canTingButton SG_imagePositionStyle:(SGImagePositionStyleRight) spacing:10];
        weakSelf.restaurantId = weakSelf.canTingArray[0][@"restaurantId"];
        
        [weakSelf getCaiPuData];
    };
    [WINDOW addSubview:pickview];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:self.dataArray[section]];
    NSArray *arr = [NSArray arrayWithArray:dic[@"arr"]];
    if ([dic[@"isOpen"] integerValue]==1) {
        return arr.count;
    }else{
        return 0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.dataArray[indexPath.section]];
    NSMutableArray *arr = [NSMutableArray arrayWithArray:dic[@"arr"]];
    
    MOCaiPuViewCell *cell = [MOCaiPuViewCell cellWithTableView:tableView andIndexPath:indexPath];
    __weak typeof (self)weakSelf = self;
    MOCaiPuModel *model = arr[indexPath.row];
    cell.clickFoodTypeBlock = ^{
        if ([model.open integerValue]==1) {
            model.open = @"0";
        }else{
            model.open = @"1";
        }
        [arr replaceObjectAtIndex:indexPath.row withObject:model];
        [dic setObject:arr forKey:@"arr"];
        [weakSelf.tableView reloadData];
    };
    cell.model = model;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:self.dataArray[indexPath.section]];
    NSArray *arr = [NSArray arrayWithArray:dic[@"arr"]];
    return [MOCaiPuViewCell heightForMOCaiPuViewCellAndModel:arr[indexPath.row]];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 54;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00001;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary:self.dataArray[section]];
    
    UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 54)];
    [backButton setBackgroundColor:[UIColor whiteColor]];
    backButton.tag = section;
    [backButton addTarget:self action:@selector(clickSectionOpenButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *dateLabel = [[UILabel alloc]initWithFrame:CGRectMake(23, 0, 150, 54)];
    dateLabel.font = FONT_SIZE(15);
    dateLabel.textColor = KBlackColor_2A2A2A;
    dateLabel.text = dic[@"name"];
    [backButton addSubview:dateLabel];
    
    UIButton *rightButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-20-15, 0, 20, 54)];
    rightButton.titleLabel.font = FONT_SIZE(15);
    [rightButton setTitleColor:KBlackColor_2A2A2A forState:UIControlStateNormal];
    rightButton.userInteractionEnabled = NO;
    if ([dic[@"isOpen"] integerValue]==1) {
        [rightButton setImage:IMAGE(@"can_top") forState:UIControlStateNormal];
    }else{
        [rightButton setImage:IMAGE(@"can_right") forState:UIControlStateNormal];
    }
    [backButton addSubview:rightButton];
    
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 53, SCREEN_WIDTH, 0.5)];
    line.backgroundColor = KGrayColor_ededed;
    [backButton addSubview:line];
    if ([dic[@"isOpen"] integerValue]==1) {
        line.hidden = YES;
    }else{
        line.hidden = NO;
    }
    
    return backButton;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
#pragma mark - 设置顶头分割线
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        if (@available(iOS 8.0, *)) {
            [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        if (@available(iOS 8.0, *)) {
            [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}


#pragma mark -懒加载
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - StatusBarAndNavigationBarHeight) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorColor = KGrayColor_ededed;
        _tableView.backgroundColor = KGrayColor_f8f8f8;
    }
    return _tableView;
}

@end
